package top.kaoshanji.r1ch05c;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * 代码清单-r1ch05c-172页a：通过DefaultListableBeanFactory动态添加Bean
 * @author kaoshanji
 * ^_^
 * create time 2025/5/6 16:32
 */
@Component
public class UserServiceFactoryBean implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

        // 将 ConfigurableListableBeanFactory 转换为 DefaultListableBeanFactory
        DefaultListableBeanFactory bf = (DefaultListableBeanFactory) beanFactory;

        // 通过 BeanDefinitionBuilder 创建Bean定义
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserService.class);

        // 设置属性userDao，此属性引用已经定义的bean：userDao
        beanDefinitionBuilder.addPropertyReference("userDao", "userDao");

        // 注册Bean定义
        bf.registerBeanDefinition("userService1", beanDefinitionBuilder.getRawBeanDefinition());

        // 直接注册一个Bean实例
        bf.registerSingleton("userService2", new UserService());

    }

}
